package com.atguigu05.communication;

/**
 * ClassName: PersonTest
 * Description:
 *  案例：使用两个线程打印 1-100。线程1, 线程2 交替打印
 * @Author liu
 * @Create 2024/11/17 15:13
 * @Version 1.0
 */
class PrintfNumder implements Runnable{
    private int number = 1;
    //同步监视器
    Object obj = new Object();
    @Override
    public void run() {
        synchronized (obj){
            while (true) {

                if (number <= 100) {
                    //唤醒
                    obj.notify();

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName()
                            + ":" + number);
                    number++;

                    //阻塞
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                } else {
                    break;
                }
            }


        }

    }
}

public class PrintNumderTest {
    public static void main(String[] args) {

        PrintfNumder p = new PrintfNumder();

        Thread t1 = new Thread(p,"线程1");
        Thread t2 = new Thread(p,"线程2");

        t1.start();
        t2.start();

    }
}
